import { createApp } from 'vue'
import './style.css'
import pinia from '@/stores'
import useAppStore from '@/stores/user'
import useLanguageStore from '@/stores/language'
import registerSentry from 'neuron/registers/registerSentry'
import i18n from '@/config/languages/i18n'
import { DECODE, ENCODE } from '@/tools'
import App from './App.vue'
// import "element-plus/dist/index.css";
import router from './config/router'
// import registerApollo from './registerApollo'
import Storeages from './constants/storages'

import './config/axios'

/* 判断是否为主应用 */
const isMainApp = window.top === window.self

async function bootstrap(cb: Function = () => {}) {
  // 创建应用实例
  const app = createApp(App)

  /* 安装状态管理器pinia */
  app.use(pinia)

  /* START 每当状态发生变化时，将 state 持久化到本地存储 */
  const appStore = useAppStore()
  appStore.$subscribe((mutation, state) => {
    const userStringify = ENCODE(JSON.stringify(state))
    // console.log(window.location.host, mutation, state, 'appStore subscribe')
    if (userStringify) {
      sessionStorage.setItem(Storeages.USER, userStringify)

      const iframes = document.getElementsByTagName('iframe')
      if (iframes) {
        Array.from(iframes).forEach((iframe) => {
          iframe.contentWindow?.postMessage(
            {
              cmd: 'refecth_token',
              data: state.authentication.token,
            },
            '*'
          )
        })
      }
    }
  })

  const languageStore = useLanguageStore()
  languageStore.$subscribe((mutation, state) => {
    console.log(window.location.host, state, 'languageStore subscribe')
    const langStringify = ENCODE(JSON.stringify(state))
    if (langStringify) {
      sessionStorage.setItem(Storeages.LANGUAGE, langStringify)

      const iframes = document.getElementsByTagName('iframe')
      if (iframes) {
        Array.from(iframes).forEach((iframe) => {
          iframe.contentWindow?.postMessage(
            {
              cmd: 'change_language',
              data: state.language,
            },
            '*'
          )
        })
      }
    }
  })

  /* 每当状态发生变化时，将 state 持久化到本地存储 END */

  // 持久化 应用数据
  if (isMainApp && sessionStorage[Storeages.USER]) {
    const userState = JSON.parse(DECODE(sessionStorage[Storeages.USER]) || '{}')
    const { userinfo, authentication } = userState
    appStore.login(userinfo, authentication)

    const langState = JSON.parse(
      DECODE(sessionStorage[Storeages.LANGUAGE]) || '{}'
    )
    languageStore.updateLanguage(langState.language)
  }

  await cb()

  if (import.meta.env.PROD) {
    registerSentry({
      router,
      app,
      // dsn: '/senrry_dsn',
      dsn: 'https://5e9a6aa520074b87bedbead148dfcb39@sentry.dev.neuroncloud.ai/18',
    })
  }

  /* 安装i8n */
  app.use(i18n)

  /* 安装路由 */
  app.use(router)
  await router.isReady()

  /* 挂载dom */
  app.mount('#app')
}

if (isMainApp) {
  bootstrap()
} else {
  window.addEventListener('message', async ({ data: { cmd, data } }) => {
    /* 初始化应用 */
    if (cmd === 'install_featrue_app') {
      /* 继承父应用数据 */
      bootstrap(async () => {
        const appStore = useAppStore()
        if (data.user) {
          sessionStorage[Storeages.USER] = data.user
          const userState = JSON.parse(DECODE(data.user) || '{}')
          const { userinfo, authentication } = userState
          appStore.login(userinfo, authentication)
        }

        if (data.language) {
          sessionStorage[Storeages.LANGUAGE] = data.language
          const language = JSON.parse(DECODE(data.language) || '{}')
          const languageStore = useLanguageStore()
          languageStore.updateLanguage(language.language)
        }
      })
    }

    /* 刷新token */
    if (cmd === 'refecth_token') {
      const appStore = useAppStore()
      appStore.updateToken(data)
    }

    /* 切换语言 */
    if (cmd === 'change_language') {
      const languageStore = useLanguageStore()
      languageStore.updateLanguage(data)
    }
  })
}
